package com.macro.mall.portal.service;

import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

@Service
public class MongoHealthCheckService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoClient mongoClient;

    public boolean checkMongoHealth() {
        try {
//            mongoClient.getDatabaseNames();
            mongoTemplate.executeCommand("{ ping: 1 }");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 测试MongoDB连接是否正常
     * @return true表示连接成功，false表示连接失败
     */
    public String testConnection() {
        try {
            // 方法1: 使用MongoTemplate
            mongoTemplate.executeCommand("{ ping: 1 }");

            // 或者方法2: 使用MongoClient
            // mongoClient.listDatabaseNames().first();

            return "mongo 连接成功";
        } catch (Exception e) {
            return "mongo 连接失败";
        }
    }
}
